package com.example.autumn.service.impl;

import com.example.autumn.service.IUserExService;
import com.example.autumn.utils.EmailSender;
import com.example.common.response.R;
import com.example.common.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Liaorun
 */
@Slf4j
@Service
public class IUserExServiceImpl implements IUserExService {

    @Resource
    public RedisTemplate<String, Object> redisTemplate;

    @Override
    public R sendMailCode(String mail, boolean b) {

        if (TextUtils.isEmpty(mail)) {
            return R.Error().setMsg("邮箱地址不可以为空");
        }

        String pattern = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(mail);

        if (!m.matches()) {
            return R.Error().setMsg("请检查邮箱格式");
        }

        if (b) {
            // 检查邮箱是否注册
        }

        // 反正恶意频繁调用
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String remoteAddr = request.getRemoteAddr();

        log.info("remote address ..{}", remoteAddr);

        remoteAddr = remoteAddr.replaceAll(":", "-");

        // 获取这个ip 发送了几次邮箱
        Integer alreadUseTimes = (Integer) redisTemplate.opsForValue().get(Constants.User.KEY_MAIL_CODE_IP + remoteAddr);

        if (alreadUseTimes != null) {

            // 2 小时内，最多发10次
            if (alreadUseTimes > 10) {
                return R.Error().setMsg("操作过于频繁");
            } else {

                // 没达到次数限制，还可以发，增加一次发送次数
                alreadUseTimes++;
                redisTemplate.opsForValue().set(Constants.User.KEY_MAIL_CODE_IP + remoteAddr, alreadUseTimes, 2, TimeUnit.HOURS);
            }

            redisTemplate.opsForValue().set(Constants.User.KEY_MAIL_CODE_IP + remoteAddr, 1, 2, TimeUnit.HOURS);
        } else {
            redisTemplate.opsForValue().set(Constants.User.KEY_MAIL_CODE_IP + remoteAddr, 1, 2, TimeUnit.HOURS);
        }

        // 产生验证码
        Random random = new Random();
        int mailCode = random.nextInt(99999);

        // 保证产生的验证码位数为 5位
        if (mailCode < 10000) {
            mailCode += 10000;
        }
        // 记录验证码
        redisTemplate.opsForValue().set(Constants.User.KEY_MAIL_CODE + mail, mailCode, 5, TimeUnit.MINUTES);
        // 发送验证码
        EmailSender.sendMailCode(mail, "验证码：" + mailCode + ",五分钟内有效");
        return R.SUCCESS("邮箱验证码发送成功");
    }
}
